<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.util.List"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
 <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%--
index.jsp 知识点： 
	下拉框的选择和设置
	ajax发送请求
	<c:if>标签使用
	$('#loginForm').serialize();  //得到整个表单的数据
	两个div标签的并排摆放
	通过多次的ajax请求实现动态的展示全部表格数据
--%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Transitional//EN">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" language="javascript" src="<%=path %>/resources/js/jquery-1.4.3.js"></script>
<script type="text/javascript">

/*
	执行sql查询
*/
function executeSql(){
	var sqlValue=$("#sql").val();
	var sql=$.trim(sqlValue);
	//1检查数据是否合格
	if(sql==""){
		alert("提交的sql不能为空!");
		return ;
	}
	if(confirm("确定提交sql语句到后台吗?")){
		var exed='<%=path %>/resources/images/execute.gif';
		$("#exe_img").attr("src",exed);
		var time1 = new Date().getTime();
		var url="<%=path %>/executeSql";
		$.ajax({
			type : "POST",
			url :url,
			data :{'sql':sqlValue},
			dataType : "json",
			error : function(json) {
				alert("执行程序异常:"+json);
			},
			success : function(data) {
/*				data=eval('('+data+')'); */
				var exe='<%=path %>/resources/images/execute.gif';
				$("#exe_img").attr("src",exe)
				var needTime=(new Date().getTime()-time1)/1000;
				$("#time").html(needTime);
				showMessage(data);
			}
		});
	}
}
/**
	查询导出Excel
**/
function exportExcel(){
	//var sqlValue=$("#sql").val();
	//var sql=$.trim(sqlValue);
	//1检查数据是否合格
	if(confirm("确定导出当前查询列表的EXCEL吗?")){
		//var exed=nginxDomainPath+'/images/executed.gif';
		//$("#exe_img").attr("src",exed);
		//var time1 = new Date().getTime();
		//提交表单导出数据
		var form1=window.document.form1;
		form1.action="<%=path %>/exportExcel";
		form1.submit();
	}
}

//ajax返回信息处理
function showMessage(data){
	if(data.result){
/**		$("#msg").css("display","none"); **/
		if(data!=null && data.operation=="1"){
			//SELECT
			//不需要提交,需要展示表头和数据
			$("#operation_select").css("display","block");
			$("#operation_dll").css("display","none");
			$("#operation_update").css("display","none");
			jsonToList(data.resultMap);
		}else if(data!=null && data.operation=="2"){
			//UPDATE 需要展示更新行数
			$("#operation_select").css("display","none");
			$("#operation_dll").css("display","none");
			$("#operation_update").css("display","block");
			var str="<span style='color:green'>"+"受影响行数:"+data.row+"</span>";
			$("#operation_update").html(str);
		}else if(data!=null && data.operation=="3"){
			//DLL 需要提示成功失败信息
			$("#operation_select").css("display","none");
			$("#operation_update").css("display","none");
			$("#operation_dll").css("display","block");
			var str="<span style='color:green'>执行成功!</span>";
			$("#operation_dll").html(str)
		}
		$("#operation").attr("value",data.operation);
		$("#msg").html("连接成功");
		$("#msg").css("display","inline");  
	}else{
	 	//出现错误打印错误
		$("#operation_select").css("display","none");
		$("#operation_update").css("display","none");
		$("#operation_dll").css("display","none");
		$("#msg").css("display","block");
	 	$("#msg").html(data.errorDetail);
	}
}

function jsonToList(jsonData){
	var fieldList=jsonData["fieldList"];
	var valueList=jsonData["valueList"];
	//设置参数
	var pageSql=jsonData["pageSql"];
	var currentPage=jsonData["currentPage"];
	var totalPages=jsonData["totalPages"];
	var totalCount=jsonData["totalCount"];
	//是否有总页数
	if(totalPages!=null){
		$("#totalPages").attr("value",totalPages);
		$("#totalPages_show").html(totalPages);
	}
	if(totalCount!=null){
		$("#totalCount_show").html(totalCount);
	}
	$("#currentPage").attr("value",currentPage);
	if(currentPage==-1||currentPage==0){
		$("#currentPage_show").html(1);
	}else{
		$("#currentPage_show").html(currentPage);
	}
	$("#pageSql").attr("value",pageSql);
	
	var trHtml="";
	//处理表头
	if(fieldList!=null && fieldList.length>0){
		trHtml=trHtml+"<tr class='z_title'>";
		for ( var i = 0; i <fieldList.length; i++) {
			var fieldObj = fieldList[i];
			trHtml=trHtml+"<td align=center>&nbsp;"+fieldObj["name"]+"&nbsp;</td>";
		}
		trHtml=trHtml+"</tr>"
	}
	//处理数据
	if(valueList!=null && valueList.length>0){
		for ( var j = 0; j <valueList.length; j++) {
			trHtml=trHtml+"<tr class='z_tr'>";
			var valueObj = valueList[j];
			if(j==0){
				//alert("=="+valueObj["ID"]);
			}
			if(fieldList!=null && fieldList.length>0){
				for ( var k = 0; k <fieldList.length; k++) {
					var fieldObj = fieldList[k];
					var enname=fieldObj["name"];
					if(valueObj[enname]){
						trHtml=trHtml+"<td align='center'>"+valueObj[enname]+"</td>";
					}else{
						trHtml=trHtml+"<td align='center'>&nbsp;</td>";
					}
					
				}
			}
			trHtml=trHtml+"</tr>"
		}
	}	

	$("#grid").html(trHtml);
}
function jsonPageToList(jsonData){
	var fieldList=jsonData["fieldList"];
	var valueList=jsonData["valueList"];
	//设置参数
	//var pageSql=jsonData["pageSql"];
	var currentPage=jsonData["currentPage"];
	//var totalPages=jsonData["totalPages"];
	//$("#pageSql").attr("value",pageSql);
	//是否有总页数
	/***
	if(totalPages!=null){
		$("#totalPages").attr("value",totalPages);
	}
	***/
	$("#currentPage").attr("value",currentPage);
	if(currentPage==-1||currentPage==0){
		$("#currentPage_show").html(1);
	}else{
		$("#currentPage_show").html(currentPage);
	}
	var trHtml="";
	/***
	//处理表头
	if(fieldList!=null && fieldList.length>0){
		trHtml=trHtml+"<tr class='z_title'>";
		for ( var i = 0; i <fieldList.length; i++) {
			var fieldObj = fieldList[i];
			trHtml=trHtml+"<td align=center>&nbsp;"+fieldObj["name"]+"&nbsp;</td>";
		}
		trHtml=trHtml+"</tr>"
	}
	***/
	//处理数据
	if(valueList!=null && valueList.length>0){
		for ( var j = 0; j <valueList.length; j++) {
			trHtml=trHtml+"<tr class='z_tr'>";
			var valueObj = valueList[j];
			if(j==0){
				//alert("=="+valueObj["ID"]);
			}
			if(fieldList!=null && fieldList.length>0){
				for ( var k = 0; k <fieldList.length; k++) {
					var fieldObj = fieldList[k];
					var enname=fieldObj["name"];
					if(valueObj[enname]){
						trHtml=trHtml+"<td align='center'>"+valueObj[enname]+"</td>";
					}else{
						trHtml=trHtml+"<td align='center'>&nbsp;</td>";
					}
					
				}
			}
			trHtml=trHtml+"</tr>"
		}
	}	
	$("#grid").append(trHtml);
}
/***
 * 显示下一页
 */
function showNextPage(type){
	//所有的页数
	var pageSql=$("#pageSql").val();
	var currentPage=$("#currentPage").val();
	var totalPages=$("#totalPages").val();
	var operation=$("#operation").val();
	var nextPage=parseInt(currentPage);
	var total=parseInt(totalPages);
	if(nextPage<total){
		nextPage=nextPage+1;
	}else{
		$("#turnBtn").css("display","none");
		return;
	}
	if(type=='all'){
		if(!isStop){
			$("#turnBtn").css("display","block");
		}else{
			return;
		}
	}
	$("#loading").css("display","block");
	//1检查数据是否合格
	var url="<%=path %>/nextPage";
	$.ajax({
		type : "POST",
		url :url,
		data :{'type':type,"currentPage":nextPage,"pageSql":pageSql,"totalPages":totalPages,"operation":operation},
		dataType : "json",
		error : function(json) {
			alert("执行程序异常:"+json);
		},
		success : function(data) {
			$("#loading").css("display","none");
			if(data.result){
				//alert(data.resultInfo);
				jsonPageToList(data.resultMap);
				if(type=="all" && isStop==false){
					var t=setTimeout("showNextPage('all')",500);
				}
			}else{
				alert(data.resultInfo);
				$("#operation_select").css("display","none");
				$("#operation_update").css("display","none");
				$("#operation_dll").css("display","none");
				$("#msg").css("display","block");
			 	$("#msg").html(data.errorDetail);
			}
		}
	});
}
var isStop=false;
function turnButton(){
	isStop=true;
	$("#turnBtn").css("display","none");
}

/**
	ajax发送数据库连接的信息
**/
function loginClick(){
	var formStr=$('#loginForm').serialize();
	$.ajax({
		type : "POST",
		url :"<%=path %>/login",
		data :formStr,
		dataType : "json",
		error : function(json) {
			alert("执行程序异常:"+json);
		},
		success : function(data) {
			if(data.result){
				alert(data.resultInfo);
			}else{
				if(data.type=="oraDBs"){
					$("#oneIp").css("display","none");
					$("#oracleDBs").css("display","inline");
					$("#oracleDBs > #oracleUrl").val(data.oracleUrl);
				}else{
					$("#oracleDBs").css("display","none");
					$("#oneIp").css("display","inline");
					$("#ipAdd").val(data.ipAdd);
					$("#db").val(data.db);
				}
				$("#msg").html(data.msg);
				$("#username").val(data.username);
				$("#password").val(data.password);
			}
		}
	});
}

function testJSON(){
		$.ajax({ 
			type: "post", 
			url: "JSON", 
			dataType: "json", 
            success: function (data) {
/*            	$("#training_number").text(data.training_number);  */
				alert(data.name);
			}
		});
}

/**
	根据选择的历史记录自动输入到输入框
**/
function fnChange(){
	var obj=document.getElementById('selectLog');
	var index=obj.selectedIndex; 
	var value=obj[index].value;
	var strs= new Array(); //定义一数组
	strs=value.split("&"); //字符分割 
	$("#type").find("option[value="+strs[0]+"]").attr("selected",true);
	if(strs[0]=="oraDBs"){
		$("#oneIp").css("display","none");
		$("#oracleDBs").css("display","inline");
		$("#oracleDBs > #oracleUrl").val(strs[1]);
		$("#username").val(strs[2]);
		$("#password").val(strs[3]);
	}else{
		$("#oracleDBs").css("display","none");
		$("#oneIp").css("display","inline");
		$("#oneIp > #ipAdd").val(strs[2]);
		$("#oneIp > #db").val(strs[3]);
		$("#username").val(strs[1]);
		$("#password").val(strs[4]);
	}
	$("#msg").html("");
}
/**
	根据数据库类型切换显示输入框
*/
function typeChange(){
	var obj=document.getElementById('type');
	var index=obj.selectedIndex; 
	var value=obj[index].value;
	if(value=="oraDBs"){
		$("#oneIp").css("display","none");
		$("#oracleDBs").css("display","inline");
		$("#oracleDBs > #oracleUrl").val("");
	}else{
		$("#oracleDBs").css("display","none");
		$("#oneIp").css("display","inline");
		$("#oneIp > #ipAdd").val("");
		$("#oneIp > #db").val("");
	}
	$("#username").val("");
	$("#password").val("");
	$("#msg").html("");
}

function loadSelect(){
	//根据数据设置下拉框默认显示的值
	$("#type").find("option[value='${type}']").attr("selected",true);
	loadXml();
}
/**
	加载数据库历史连接记录
**/
function loadXml(){
		$.ajax({
		type : "POST",
		url :"<%=path %>/loadXml",
		data :{},
		dataType : "json",
		error : function(json) {
			alert("执行程序异常:"+json);
		},
		success : function(data) {
			if(data.deleteBool){
				var list=data.history;
				var htmlStr=""; 
				for(var i=0;i<list.length;i++){
					var dom=list[i];
					var valuestr=dom.value;
					var keystr=dom.key;
					htmlStr=htmlStr+"<option value='"+valuestr+"'><div style='display:block; width: 50px;' ><div style='width:40px'>"+keystr+"<div></div></option>";
				}
				$('#selectLog').html(htmlStr);
			}
		}
	});
}

/**
	删除连接记录
*/
function deleteOpt(){
	var obj=document.getElementById('selectLog');
	var index=obj.selectedIndex; 
	if(index==-1){
		alert("请选中要删除的记录");
		return;
	}
	var value=obj[index].value;
	var key=obj[index].text;
	$.ajax({
		type : "POST",
		url :"<%=path %>/deleteXml",
		data :{'key':key,"value":value},
		dataType : "json",
		error : function(json) {
			alert("执行程序异常:"+json);
		},
		success : function(data) {
			if(data.deleteBool){
				alert("删除成功");
				var list=data.history;
				var htmlStr=""; 
				for(var i=0;i<list.length;i++){
					var dom=list[i];
					var valuestr=dom.value;
					var keystr=dom.key;
					htmlStr=htmlStr+"<option value='"+valuestr+"'><div style='display:block; width: 50px;' ><div style='width:40px'>"+keystr+"<div></div></option>";
				}
				$('#selectLog').html(htmlStr);
			}else{
				alert("删除失败");
			}
		}
	});
}
</script>
<STYLE type=text/css>
BODY {
	BACKGROUND: #e3f0ed
}
.zx{
	float:left;
	height: 20px;
	width: 20px;
	
}
.zx a:hover{
	float:left;	
	height: 20px;
	width: 20px;
	background-color: #a6ceda;
}
.z_table{
	border: 1px solid #e0dcdc;
	border-bottom:none;
	border-right:none;
	background-color: #fafafa;
}
.z_table td{border-bottom: 1px solid #e0dcdc; border-right: 1px solid #e0dcdc;}
.z_title {
	BACKGROUND-COLOR: #eae7e7; HEIGHT: 28px
}
.z_tr {
	HEIGHT: 25px
}
.z_button{
	line-height: 24px;
	background-image: url(<%=path %>/resources/images/button_b.gif);
	background-repeat: no-repeat;
	text-align: center;
	float: left;
	height: 24px;
	width: 65px;
	font-family: "微软雅黑";
	font-size: 13px;
}
a img,img{border:0 none; }
</STYLE>
</HEAD>
<BODY onload="javascript:loadSelect();">
<div>
	<div  id="mainDiv" style="width:80%;float:left;   padding:10px;">
	<div style="padding-left:20px;">
<!-- 		<div>${ type}</div>
 	<button onclick="testJSON()">测试</button>  -->
		<form action="login" method="post" id="loginForm" name="loginForm">
			数据库：<select id="type" name="type" style="width: 72px" onchange="typeChange()">
				<option value="oracle">oracle</option>
				<option value="oraDBs">oracle集群</option>
			<!-- 	<option value="mysql" >mysql</option>   -->
			</select>
			<div id="oneIp" <c:if test="${ empty type||type=='mysql'||type=='oracle'}"> style="display: inline;" </c:if><c:if test="${type=='oraDBs'}"> style="display: none;" </c:if> >	
			IP地址：<input id="ipAdd" name="ipAdd" value="${ ipAdd}" type="text" width="80" size="15">   
		 	数据库ID：<input id="db" name="db" size="10" value="${ db}" size="10"> 
		 	</div>
		 	<div id="oracleDBs" <c:if test="${empty type|| type=='mysql'||type=='oracle'}"> style="display: none;" </c:if><c:if test="${type=='oraDBs'}"> style="display: inline;" </c:if> >
		 		URL：<input id="oracleUrl" name="oracleUrl" value="${ oracleUrl}" type="text" size="48">  
		 	</div>
		 	用户名：<input id="username" name="username" value="${ username}" size="10"> 
		 	密码：  <input id="password" name="password" value="${ password}" style="font-weight: 50" size="10">
			<input type="button" value="连接数据库" name="BTlogin" onclick="loginClick()" size="50">	
			<span style="color:Red;" id="msg" >${msg}</span>					
		</form>
	</div>
<DIV class="ui-layout-north" >

<div style="padding-left:20px;margin-top: 5px;">
<a href="javascript:;" onclick='executeSql();' style="font-size: medium" id="exe_a">
<img src="<%=path %>/resources/images/execute.gif" width="65" height="24" style=" margin-top:2px; margin-left:2px;" id="exe_img">
</a>
<span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 耗时:<span style="color:red" id="time">0</span>秒
</span>
<br/>
</div>
</DIV>  
<DIV class="ui-layout-center" >
<form action="" method="POST" name="form1" id="form1">
	<div style="padding-left:20px;margin-top: 5px;">
	<textarea rows="" cols="" style="width: 90%;height:235px;font-size: medium" id="sql"></textarea>
	<input type="hidden" name="operation" id="operation" value=""/>
	<input type="hidden" name="currentPage" id="currentPage" value=""/>
	<input type="hidden" name="pageSql" id="pageSql" value=""/>
	<input type="hidden" name="totalPages" id="totalPages" value=""/>
	<input type="hidden" name="turnValue" id="turnValue" value="start"/>
	<input type="hidden" name="excelType" id="excelType" value="excel"/>
	</div>
</form>
</DIV>
<DIV class="ui-layout-west" >
<div style="padding-left:20px;margin-top: 5px;">
	<div id="operation_select" style="display:none;font-size: medium;">
		<div>
			<div class="z_button" style="font-size: medium;">
				<a href="javascript:;" onclick="showNextPage('next');" >
					下一页
				</a>
			</div>
			<div class="z_button" style="margin-left:15px;font-size: medium;">
				<a href="javascript:;" onclick="isStop=false;showNextPage('all');" >
					全  部
				</a>
			</div>
			<div class="z_button" style="margin-left:15px;font-size: medium;">
				<a href="javascript:;" onclick="exportExcel()" >
					导出EXCEL
				</a>
			</div>
			<div class="z_button" style="margin-left:15px;font-size: medium;display: none" id="turnBtn">
				<a href="javascript:;" onclick="turnButton();" id='turnInfo' >停止</a>
			</div>
			<div style="float: left;height: 24px;margin-left:60px;font-size: medium;color: green">
			总数:<span id="totalCount_show"></span>,总页数:<span id="totalPages_show"></span>当前页:<span id="currentPage_show"></span> &nbsp;&nbsp;&nbsp;&nbsp;(注:每次多显示20条)
			</div>
		</div>
		<div style="float:left; position:absolute; width:89%; height:260px; margin-left:-89%;display: none;" id="loading">
		  <table border="0" align="center" cellpadding="0" cellspacing="0" height="220">
		    <tr>
		      <td align="center" valign="bottom" style="font-family:'微软雅黑'; font-size:20px; color:#03F;">数据加载中</td>
		    </tr>
		    <tr>
		      <td><img src="<%=path %>/resources/images/loading_sql.gif" width="214" height="15"></td>
		    </tr>
		  </table>
		</div>
		<div style="width:90%; float:left; overflow:scroll; height:230px">
		<table border="0" cellpadding="0" cellspacing="0" id=grid class="z_table" >

		</table>
		</div>	
	</div>
	<div id="operation_update" style="display: none;font-size: medium;">
	</div>
	<div id="operation_dll" style="display: none;font-size: medium;">
	
	</div>
	<div id="msg2" style="display: block;color: red;font-size: medium;">
	</div>
</div>
</DIV>
</div>
<div style="width:10%;float:left;   margin-left:-80px;margin-top:48px; volume: 10" >
	<div style="width:230px;">
		连接记录：
		<div style='display: inline; float: right' >
			<input type="button" value="删除记录" name="xmlDelete" onclick="deleteOpt()" size="50">	
		</div>
	</div>
	<div align="center" style="margin-top:6px;">
		<select id="selectLog" name="selectLog" style="width: 230px; height: 240px" size="15" onchange="fnChange()">
		<%-- 
			<c:choose>
				<c:when test="${!empty history}">
				
					<!--  
					<c:forEach items="${history}" var="h">
						<option value="${h.value}">${h.key }</option>
					</c:forEach>
					-->
					<!--  
					<c:forEach var="index" begin="0" end="${fn:length(history)-1}">
						<option value="${history[index].value}">
							${history[index].key }
						</option>
					</c:forEach>
					-->
				</c:when>
				<c:otherwise>
					<option value="0">暂无记录</option>
				</c:otherwise>
			</c:choose>
		--%>  
		</select>
	</div>
</div>
</div>
</BODY>
</HTML>